package com.ly.mpayment.rest.up.guochuang;

import com.alibaba.fastjson.JSONObject;
import com.ly.mpayment.core.secuity.MD5;
import com.ly.mpayment.core.util.*;
import com.ly.mpayment.persist.entity.UpOrder;
import com.ly.mpayment.persist.entity.UpShopInfo;
import com.ly.mpayment.persist.entity.UpShopProduct;
import com.ly.mpayment.persist.service.downrechargeflow.IDownRechargeFlowService;
import com.ly.mpayment.persist.service.downshopinfo.IDownShopInfoService;
import com.ly.mpayment.persist.service.uporder.IUporderService;
import com.ly.mpayment.persist.service.upshopinfo.IUpShopInfoService;
import com.ly.mpayment.rest.recharge.RechargeRest;
import com.ly.mpayment.rest.up.util.Util;
import org.apache.log4j.Logger;
import org.mortbay.util.MultiMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Component
@Path("guochuang")
public class GuoChuangRest {
    Logger logger = Logger.getLogger(GuoChuangRest.class);

    @Autowired
    IUporderService upOrderService;

    @Autowired
    IDownRechargeFlowService flowService;

    @Autowired
    IDownShopInfoService shopService;

    @Autowired
    IUpShopInfoService upShopInfoService;


    /**
     * 成功订单有凭证
     * {"account":"%s","evidence":"%s","evidenceType":"%s","id":"%s","inTime":"%s","money":"%s","outerId":"%s","status":"%s"}&ts=%s&key=%s
     * 失败订单无凭证
     * {"account":"%s","id":"%s","inTime":"%s","money":"%s","outerId":"%s","status":"%s"}&ts=%s&key=%s
     * @param data
     * @return
     */
    @Path("callBack")
    @POST
    public String callBack(@RequestBody String data) {
        //{"account":"18782435842","evidence":"N/A","evidenceType":"","id":"D2022091708461797318","inTime":"2022/09/17 08:51:28","money":"1","outerId":"2c922ab98345d7b5018348e911ca4292","status":"SUCCESS"}
        logger.info("guochuang_callback:" + data);
        if (!StringUtils.isBlank(data)) {
            JSONObject multiMap = JSONObject.parseObject(data);
            UpOrder order = upOrderService.findById(multiMap.getString("outerId"));
            if(order == null){
                logger.info("订单不存在:"+data);
                return "订单不存在";
            }
            final UpShopInfo upShopInfo = this.upShopInfoService.findByUserId(order.getUserOrder().getUseruuid());
            if(upShopInfo == null){
                logger.info("渠道用户不存在:"+data);
                return "failt";
            }

            //if(!multiMap.getString("szVerifyString").equals(MD5.md5("szAgentId="+upShopInfo.getAppId()+"&szOrderId="+order.getUporderuuid()+
            //        "&szPhoneNum="+multiMap.getString("szPhoneNum")+"&nDemo="+multiMap.getString("nDemo")+"&fSalePrice="+multiMap.getString("fSalePrice")
            //        +"&nFlag="+multiMap.getString("nFlag")+"&szKey="+upShopInfo.getUpkey()).toLowerCase())){
            //    logger.info("签名错误:"+data);
            //    return "failt";
            //}


            if (order != null && multiMap.getString("status").equals("SUCCESS") && order.getStatus() == Config.status[0]) {
                order.setRemark(multiMap.containsKey("evidence") ? multiMap.getString("evidence") : multiMap.getString("status"));
                RechargeRest.successUpOrder.add(order);
                multiMap.clear();
                multiMap.put("code","SUCCESS");
                return multiMap.toString();
            } else if (order != null && order.getStatus() == Config.status[0] && multiMap.getString("status").equals("FAIL")) {
                order.setRemark(multiMap.getString("status"));
                RechargeRest.failtUpOrder.add(order);
                multiMap.clear();
                multiMap.put("code","SUCCESS");
                return multiMap.toString();
            } else {
                this.upOrderService.addOrderMsg(order,multiMap.getString("status"));
                logger.info("guochuang_not_found_order:" + multiMap.getString("status") + "," + (order == null ? "" : order.getUpphonenum()));
            }
        }
        return "0";
    }


    //上海(3), (4), (5), (6), (7), (8), (9), (10), (11), (12), (13),
    // (14), (15), (16), 海南(17), 安徽(18), 江西(19), 江苏 (20), 浙江(21), 福建(22), 陕西(23), 甘肃(24),
    //宁夏(25), 云南 (26), 贵州(27), 四川(28), 青海(29), 新疆(30), 西藏(31)
    Map<String,String> pros = new HashMap<String,String>(){{
        put("北京","1");
        put("天津","2");
        put("上海","3");
        put("重庆","4");
        put("内蒙古","5");
        put("黑龙江","6");
        put("吉林","7");
        put("辽宁","8");
        put("河南","9");
        put("河北","10");
        put("山东","11");
        put("山西","12");
        put("湖南","13");
        put("湖北","14");
        put("广东","15");
        put("广西","16");
        put("海南","17");
        put("安徽","18");
        put("江西","19");
        put("江苏","20");
        put("浙江","21");
        put("福建","22");
        put("陕西","23");
        put("甘肃","24");
        put("宁夏","25");
        put("云南","26");
        put("贵州","27");
        put("四川","28");
        put("青海","29");
        put("新疆","30");
        put("西藏","31");

    }};
    /**
     * 订单提交
     *
     * (1)(2),
     * @param order
     * @param shop
     */
    public void commitOrder(UpOrder order, UpShopInfo shop) {

        JSONObject get = new JSONObject();
        get.put("service","order.phone.charge");
        get.put("userId",shop.getAppId());
        get.put("ts",System.currentTimeMillis());
        JSONObject data = new JSONObject();
        data.put("phone", order.getUpphonenum());
        //2edb5b9c-9f99-11e7-9dc0-fcaa1456507e 中国移动
        //2ee16927-9f99-11e7-9dc0-fcaa1456507e 中国联通
        //2ee70961-9f99-11e7-9dc0-fcaa1456507e 中国电信
        data.put("phoneType", order.getOperators().equals("2edb5b9c-9f99-11e7-9dc0-fcaa1456507e") ? "11" :
                order.getOperators().equals("2ee16927-9f99-11e7-9dc0-fcaa1456507e") ? "21" :
                        order.getOperators().equals("2ee70961-9f99-11e7-9dc0-fcaa1456507e") ? "31" : 4);
        data.put("money", order.getUpShopPro().getUpfacevalue());
        data.put("speed", "0");
        data.put("outerId", order.getUporderuuid());
        data.put("callBackUrl", shop.getOrderCallAddress());
        data.put("provId", pros.get(order.getProvince()));

        String getStr = String.format("service=%s&userId=%s&ts=%s&phone=%s&phoneType=%s" +
                        "&money=%s&outerId=%s&callBackUrl=%s&speed=%s&provId=%s&key=%s",get.getString("service"),
                shop.getAppId(),get.getString("ts"),order.getUpphonenum(),data.getString("phoneType"),
                order.getUpShopPro().getUpfacevalue(),order.getUporderuuid(),shop.getOrderCallAddress(),"0",
                data.getString("provId"),shop.getUpkey());

        get.put("sign",MD5.md5(getStr).toUpperCase());

        String result = HttpClient.postUrlFrom(shop.getOrderCommitAddress().concat("?").concat(StringSort.jsonToString(get)), StringSort.jsonToString(data));
        logger.info("commitOrder_guochuang:" + result + ":" + StringSort.jsonToString(data)+"，"+StringSort.jsonToString(get)+","+shop.getOrderCommitAddress().concat("?").concat(getStr));
        if (!StringUtils.isBlank(result)) {
            try{
                JSONObject json = JSONObject.parseObject(result);
                if (json.containsKey("code") && json.getString("code").equals("SUCCESS")) {
                    this.upOrderService.updateUpOrderMsg(order,json.getString("id"),json.containsKey("code") ?
                            json.getString("code") : "");
                } else if (json.containsKey("code") && errorCode.contains(json.getString("code"))){
                    order.setRemark(json.getString("code"));
                    RechargeRest.failtUpOrder.add(order);
                } else {
                    upOrderService.updateUpOrderArtificial(order, "",json.getString("code")+"人工");
                }
            }catch (Exception e){
                e.printStackTrace();
                upOrderService.updateUpOrderArtificial(order,"","提单失败,人工");
            }
        } else {
            this.upOrderService.updateUpOrderArtificial(order, "","人工");
            logger.info("commitOrder_error:" + order.getUpphonenum());
        }
    }

    public static void main(String[] args) {

        //new GuoChuangRest().commitOrder(new UpOrder(){{
        //    setUporderuuid("xxxxx");
        //    setUpphonenum("18782435842");
        //    setProvince("四川");
        //    setOperators("2edb5b9c-9f99-11e7-9dc0-fcaa1456507e");
        //    setUpShopPro(new UpShopProduct(){{
        //        setUpfacevalue("10");
        //    }});
        //}},new UpShopInfo(){{
        //    setOrderCommitAddress("http://39.98.30.44:34341/hbgc/zz003");
        //    setAppId("cdkks8888");
        //    setUpkey("TWNLS3FxYVZnZkhH");
        //    setOrderStatusAddress("http://119.23.55.151:8181/mpayment/client/guochuang/callBack");
        //    setOrderCallAddress("http://119.23.55.151:8181/mpayment/client/guochuang/callBack");
        //}});

        //new GuoChuangRest().queryOrder(new UpOrder(){{
        //    setUporderuuid("2c922ab98345d7b5018348e911ca4292");
        //    setUpphonenum("18782435842");
        //    setProvince("四川");
        //    setOperators("2edb5b9c-9f99-11e7-9dc0-fcaa1456507e");
        //    setUpShopPro(new UpShopProduct(){{
        //        setUpfacevalue("10");
        //    }});
        //}},new UpShopInfo(){{
        //    setOrderCommitAddress("http://39.98.30.44:34341/hbgc/zz003");
        //    setAppId("cdkks8888");
        //    setUpkey("TWNLS3FxYVZnZkhH");
        //    setOrderStatusAddress("http://39.98.30.44:34341/hbgc/zz003");
        //    setOrderCallAddress("http://119.23.55.151:8181/mpayment/client/guochuang/callBack");
        //}});
    }

    Set<String> errorCode = new HashSet<String>(){{
        add("PARAM_EMPTY");
        add("PARAM_ERROR");
        add("PARAM_TS_TIMEOUT");
        add("USER_NOT_EXISTS");
        add("USER_AUTH_NOT_ENOUGH");
        add("IP_DENY");
        add("SIGN_ERROR");
        add("SYSTEM_ERROR_DB");
        add("FAIL");
        add("BALANCE_NOT_ENOUGH");
        add("ORDER_PRICE_ERROR");
        add("ORDER_NOT_SUPPORT_ACCOUNT");
        add("ORDER_NOT_SUPPORT_CHANNEL");
        add("DENY_ACCOUNT");
    }};

    /**
     * 订单查询
     *
     * @param upOrder
     * @param shopInfo
     */
    public void queryOrder(UpOrder upOrder, UpShopInfo shopInfo) {
        JSONObject get = new JSONObject();
        get.put("service","order.status.query");
        get.put("userId",shopInfo.getAppId());
        get.put("ts",System.currentTimeMillis());
        JSONObject data = new JSONObject();
        data.put("id", "");
        data.put("outerId", upOrder.getUporderuuid());

        String getStr = String.format("service=%s&userId=%s&ts=%s&id=%s&outerId=%s&key=%s",get.getString("service"),
                shopInfo.getAppId(),get.getString("ts"),"",upOrder.getUporderuuid(),shopInfo.getUpkey());

        get.put("sign",MD5.md5(getStr).toUpperCase());

        String result = HttpClient.postUrlFrom(shopInfo.getOrderStatusAddress().concat("?").concat(StringSort.jsonToString(get)), StringSort.jsonToString(data));
        logger.info("guochuangqueryOrder:" + StringSort.jsonToString(data) + ":" + result);
        if (!StringUtils.isBlank(result)) {
            //{"szOrderId":"2c99e0237941a983017941aa1f5d0004","fSalePrice":47.7,"nRtn":5013,"szRtnCode":"fail","szRtnMsg":""}
            //{"code":"SUCCESS","id":"D2022091709131012077","outerId":"2c922ab9834901190
            //1834901ad920084","account":"18782435842","money":"0","status":"PROCESSING","inTime":"2022-09-17 09:18:00"}
            JSONObject jsonD = JSONObject.parseObject(result);
            if (jsonD.containsKey("code") && jsonD.getString("code").equals("SUCCESS") ) {
                UpOrder order = upOrderService.findById(jsonD.getString("outerId"));
                if (order != null && jsonD.getString("status").equals("SUCCESS") && order.getStatus() == Config.status[0]) {
                    order.setRemark( jsonD.containsKey("evidence") ? jsonD.getString("evidence") :
                            jsonD.containsKey("status") ? jsonD.getString("status") : "");
                    RechargeRest.successUpOrder.add(order);
                } else if (order != null && order.getStatus() == Config.status[0] && jsonD.getString("status").equals("FAIL") ) {
                    order.setRemark( jsonD.containsKey("status") ? jsonD.getString("status") : "");
                    RechargeRest.failtUpOrder.add(order);
                } else {
                    this.upOrderService.addOrderMsg(order,jsonD.getString("status"));
                    logger.info("guochuang_not_found_order:" + order.getUpphonenum());
                }
            } else {
                logger.info("guochuang_not_found_order:" + upOrder.getUpphonenum());
            }
        }
    }
}
